//
//  FPRootViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPRootViewController.h"
#import "FPMovieViewController.h"
#import "FPCinemaViewController.h"

#import "FPMovieHotPlayModel.h"
#import "FPPredictVidio.h"
#import "FPHotPlayModel.h"
#import "FPWillPlayModel.h"
#import "FPCinemaModel.h"
#define kHotPlayUrl @"http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=292"
#define kWillPlayUrl @"http://api.m.mtime.cn/Movie/MovieComingNew.api?locationId=292"
#define kCinemaUrl @"http://api.m.mtime.cn/OnlineLocationCinema/OnlineCinemasByCity.api?locationId=292"

@interface FPRootViewController ()<UISearchResultsUpdating,UISearchControllerDelegate>

@property (nonatomic, strong) FPMovieViewController * fpMovieVC;
@property (nonatomic, strong) FPCinemaViewController * fpCinemaVC;
@property (nonatomic, strong) MBProgressHUD * HUD;

@property (nonatomic, strong) NSMutableArray * movieArray;
@property (nonatomic, strong) NSMutableArray * hotPlayArray;
@property (nonatomic, strong) NSMutableArray * willTopArray;// 传给轮播图信息
@property (nonatomic, strong) NSMutableArray * willPlayArray;// 传给tableView信息
@property (nonatomic, strong) NSMutableArray * topVideoArray;// 预告片
@property (nonatomic, strong) NSMutableArray * predicVideoArray;
@property (nonatomic, strong) NSMutableArray * cinemaArray;// 影院信息数组
@property (nonatomic, strong) NSMutableArray * featureArray;// 影院信息中feature的内容
@property (nonatomic, strong) UISearchController * searchController;


@end

@implementation FPRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor cyanColor]];
    // Do any additional setup after loading the view.
    
    // 请求网络数据
    [self setUrl];
    
    // 创建子视图
    [self B_SubController];
    
    // 创建barbutton
    [self B_barButton];
    
    // 创建segmentcontroller
    [self B_segmentController];
    
    
    
}

/*=========================================解析网络数据=============================================*/
#pragma mark - 解析网络数据
- (void)setUrl
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view bringSubviewToFront:_HUD];
    if ([[FPNetWork shareInstance] rechability]) {
        self.HUD.labelText = @"正在加载";
        [self S_analysisHotPlay];
        [self S_analysisWillPlay];
        [self T_analysisCinema];
    }
    else
    {
        self.HUD.labelText = @"请检查网络";
    }
    
    
}
#pragma mark - 解析电影界面数据
// 解析正在热映界面数据
- (void)S_analysisHotPlay
{
    
    // 初始化数组
    self.movieArray              = [NSMutableArray array];
    self.hotPlayArray            = [NSMutableArray array];
    self.fpMovieVC.moviewArray   = [NSMutableArray array];
    self.fpMovieVC.hotMovieArray = [NSMutableArray array];
    
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kHotPlayUrl]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    
    // 开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if (data == nil) return;
                               NSMutableDictionary *hotDic  = [NSJSONSerialization JSONObjectWithData:data
                                                                       options:NSJSONReadingMutableContainers error:nil];
        
                               FPHotPlayModel * model       = [FPHotPlayModel MovieHotPlayWithDictionary:hotDic];
                               [self.movieArray addObject:model];
                               self.fpMovieVC.moviewArray   = self.movieArray;//----->外面大model
                               NSArray *array               = [hotDic objectForKey:@"movies"];
                               for (NSDictionary *dic in array) {
                                   FPMovieHotPlayModel * hotModel = [FPMovieHotPlayModel MovieHotPlayWithDictionary:dic];
                                   NSDictionary * nearestDic = [dic objectForKey:@"nearestShowtime"];
                                   hotModel.isTicket               = (BOOL)nearestDic[@"isTicket"];
                                   hotModel.nearestCinemaCount     = (int)nearestDic[@"nearestCinemaCount"];
                                   hotModel.nearestShowDay         = (int)nearestDic[@"nearestShowDay"];
                                   hotModel.nearestShowtimeCount   = (int)nearestDic[@"nearestShowtimeCount"];
                                   [self.hotPlayArray addObject:hotModel];
                                   self.fpMovieVC.hotMovieArray = self.hotPlayArray;//----->里面小model
                               }
                               [_fpMovieVC.hotTableView reloadData];
                               [self.HUD hide:YES afterDelay:1];
                           }];
}

// 解析即将上映界面数据
- (void)S_analysisWillPlay
{
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kWillPlayUrl]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    // 开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                        completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                            
                            // 初始化数组
                            self.willTopArray             = [NSMutableArray array];// 存放顶部信息数组
                            self.willPlayArray            = [NSMutableArray array];// 存放即将上映数组
                            self.topVideoArray            = [NSMutableArray array];// 存放顶部预告片
                            self.predicVideoArray         = [NSMutableArray array];// 存放即将上映预告片
                            self.fpMovieVC.willPlayArray  = [NSMutableArray array];// 传值给fpMovie界面
                            self.fpMovieVC.willTopArray   = [NSMutableArray array];// 传值给fpMovie界面
                            self.fpMovieVC.videoArray     = [NSMutableArray array];// 传值给fpTrailer界面
                            
                            if (data == nil) return;
                            // 得到最外层大字典
                            NSMutableDictionary *willDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                            // 获得字典里面的数组
                            NSArray *attentionArray          = [willDic objectForKey:@"attention"];
                            // 遍历数组获取里面的数据(字典形式存放)
                            [attentionArray enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
                                FPWillPlayModel *model       = [FPWillPlayModel willPlayModelWithDictionary:dic];
                                model.ID                     = (NSInteger)[dic objectForKey:@"id"];
                                [self.willTopArray addObject:model];
                                NSArray *preArray            = [dic objectForKey:@"videos"];
                                [preArray enumerateObjectsUsingBlock:^(NSDictionary *preDic, NSUInteger idx, BOOL *stop) {
                                    FPPredictVidio *preModel = [FPPredictVidio predictVideoWithDictionary:preDic];
                                    [self.topVideoArray addObject:preModel];
                                }];
                            }];
//                            NSLog(@"----=====----%ld",_topVideoArray.count);
//                            NSLog(@"----+++++----%ld",_willTopArray.count);
                            self.fpMovieVC.willTopArray      = self.willTopArray;

                            // 获得字典里面的数组
                            NSArray *moviecomingsArray       = [willDic objectForKey:@"moviecomings"];
                            // 遍历数组获取里面的数组
                            [moviecomingsArray enumerateObjectsUsingBlock:^(NSDictionary * dic, NSUInteger idx, BOOL *stop) {
                                FPWillPlayModel *model       = [FPWillPlayModel willPlayModelWithDictionary:dic];
                                [self.willPlayArray addObject:model];
//                                NSArray *preArray            = [dic objectForKey:@"videos"];
//                                [preArray enumerateObjectsUsingBlock:^(NSDictionary *preDic, NSUInteger idx, BOOL *stop) {
//                                    FPPredictVidio *preModel = [FPPredictVidio predictVideoWithDictionary:preDic];
//                                    [self.predicVideoArray addObject:preModel];
//                                    
//                                }];
                            }];
//                            self.fpMovieVC.videoArray      = self.predicVideoArray;
//                            NSLog(@"++++++--------%ld",_fpMovieVC.videoArray.count);
//                            NSLog(@"%@",_fpMovieVC.videoArray);
                            self.fpMovieVC.willPlayArray     = self.willPlayArray;
//                            NSLog(@"*******--------%ld",_predicVideoArray.count);
                            // 刷新视图;
                            [self.fpMovieVC.WillTableView reloadData];
                            [self.fpMovieVC.topTableView reloadData];
                            [_fpCinemaVC.collectionView reloadData];
                            [_fpCinemaVC.tableView reloadData];
                            
                            [self.HUD hide:YES afterDelay:1];
                            
                           }];
    

}

// 解析影院界面数据
- (void)T_analysisCinema
{
    // 初始化数组
    self.cinemaArray             = [NSMutableArray array];// 存放cinema界面影片信息
    self.featureArray            = [NSMutableArray array];// 存放cinema界面feature中的信息
    self.fpCinemaVC.cinemaArray  = [NSMutableArray array];// 传值给cinema界面
    self.fpCinemaVC.featureArray = [NSMutableArray array];// 传值给cinema界面
    
    // 创建网络请求
    [LORequestManger GET:kCinemaUrl
                 success:^(id response) {
        NSArray *array = (NSArray *)response;
        [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
            FPCinemaModel *model = [FPCinemaModel cinemaModelWithDictionary:dic];
            [self.cinemaArray addObject:model];
            
            NSDictionary *featureDic    = [dic objectForKey:@"feature"];
            FPCinemaModel *featureModel = [FPCinemaModel cinemaModelWithDictionary:featureDic];
            [self.featureArray addObject:featureModel];
        }];
        self.fpCinemaVC.cinemaArray     = _cinemaArray;
        self.fpCinemaVC.featureArray    = _featureArray;
        
        // 刷新数据
        [self.fpCinemaVC.tableView reloadData];
        [self.fpCinemaVC.collectionView reloadData];
    } failure:nil];
}

/*=========================================创建视图=============================================*/
#pragma mark - 创建视图
// 创建子视图
- (void)B_SubController
{
    self.fpCinemaVC = [[FPCinemaViewController alloc] init];
    self.fpCinemaVC.view.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight);

    [self addChildViewController:_fpCinemaVC];
    [self.view addSubview:_fpCinemaVC.view];

    self.fpMovieVC = [[FPMovieViewController alloc] init];
    self.fpMovieVC.view.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight);
    [self addChildViewController:_fpMovieVC];
    [self.view addSubview:_fpMovieVC.view];
    
    
    
}


// 添加uibarbuttonitem
- (void)B_barButton
{
    // 添加左上角barbutton
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithTitle:@"上海▽" style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    // 添加右上角button
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(rightButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    

}

// 在titlebar上创建segment
- (void)B_segmentController
{
    NSArray *titleArray = @[@"电影",@"影院"];//字面量创建数组存放segment标题
    UISegmentedControl * segment = [[UISegmentedControl alloc] initWithItems:titleArray];
    segment.frame = CGRectMake(0, 64, 200, 30);
    segment.layer.cornerRadius = 15;
    segment.layer.masksToBounds = YES;
    segment.layer.borderColor = [UIColor whiteColor].CGColor;
    segment.layer.borderWidth = 2.0;
    segment.selectedSegmentIndex = 0;
    //    segment.momentary = YES;
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segment;
//    [self segmentAction:segment];
}
/*=========================================方法实现=============================================*/
#pragma mark - 方法实现
// 点击进图地点
- (void)leftButtonAction:(UIBarButtonItem *)setter
{
    NSLog(@"点击进入城市选择地图");
    
}

// 点击进行搜索
- (void)rightButtonAction:(UIBarButtonItem *)setter
{
    NSLog(@"点击进行搜索");
    
    NSString* timeStr = @"1436880966";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    NSDate* date = [formatter dateFromString:timeStr];//将源时间字符串转化为NSDate
    
    NSDateFormatter* toformatter = [[NSDateFormatter alloc] init];
    
    [toformatter setDateFormat:@"yyyy/MM/dd h:MM:ss"];//设置目标时间字符串的格式
    
    NSString *targetTime = [toformatter stringFromDate:date];//将时间转化成目标时间字符串
    
    NSLog(@"targetTime === %@",targetTime);
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.delegate = self;
    self.searchController.searchBar.barTintColor = [UIColor blueColor];
    self.searchController.searchBar.frame = CGRectMake(0, 0, kScreenWidth, 50);
    self.searchController.searchBar.placeholder = @"请输入影片名,演员,导演";
//        [self presentViewController:_searchController animated:YES completion:nil];
}


// segment切换视图点击事件
- (void)segmentAction:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        NSLog(@"切换到电影视图");
        
    
         [UIView transitionFromView:_fpCinemaVC.view toView:_fpMovieVC.view duration:0.2 options:UIViewAnimationOptionTransitionNone completion:nil];
    

    }else{
        NSLog(@"切换到影院视图");
         [UIView transitionFromView:_fpMovieVC.view toView:_fpCinemaVC.view duration:0.2 options:UIViewAnimationOptionTransitionNone completion:nil];
    
    
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
